<?php

namespace addons\venue\controller;

use app\admin\model\venue\goods\Type;
use \app\admin\model\venue\goods\Goods as Product;
use app\common\controller\Api;
use think\Request;

class Goods extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getType','getGoods','getGoodsDetail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $config = "";

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("venue");
        parent::__construct($request);
    }

    /*
     * 获取产品分类
     */
    public function getType(){

        $data = Type::where('state',1)
                ->order('weigh', 'desc')
                ->field("id,name,image")
                ->select()
                ->each(function ($item){
                    $item->image = cdnurl($item->image,true);
                });

        $this->success('返回成功',$data);

    }

    /*
     * 获取产品列表
     */
    public function getGoods(){

        $type   = $this->request->post('type');
        $page   = $this->request->post('page')??1;  //页码
        $limit  = $this->request->post('limit')??10; //每页显示条数
        $where = '';
        if ($type){
            $where = array('category_id'=>$type);
        }
        $data = Product::where('state',1)
                ->where($where)
                ->field("id,code,title,tags,keywords,thumbnail,price,line_price,cd,cz,rl,bz,cpdj")
                ->paginate(["page"=>$page,"list_rows"=>$limit])
                ->each(function ($item){
                    $item->thumbnail = cdnurl($item->thumbnail,true);
                });

        $result = array("total" => $data->total(), "rows" => $data->items());
        $this->success('返回成功',$result);
    }

    /*
     * 获取商品详情
     */
    public function getGoodsDetail(){
        $id   = $this->request->post('id');
        if (!$id){
            $this->error("缺少商品id");
        }
        $data = Product::where('state',1)
                ->where('id',$id)
                ->field("id,code,title,tags,keywords,thumbnail,images,price,line_price,description,stock,daily,content,cd,cz,rl,bz,cpdj")
                ->find();
        if (!$data){
            $this->error("商品不存在");
        }
        $images = $data['images'];
        $a = explode(',',$images);
        foreach ($a as &$v){
            $v = cdnurl($v,true);
        }
        $data['image'] = $a;
        $data['thumbnail'] = cdnurl($data['thumbnail'],true);
        $this->success('返回成功',$data);
    }

}
